package thread;

class MyBlockingQueue{
    private String[] data=null;
    private volatile int size=0;
    private volatile int head=0;
    private volatile int tail=0;
    public MyBlockingQueue(int capacity){
        data=new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size==data.length){//这里用while为了二次验证 防止被interrupt唤醒 导致执行下面逻辑发生错误
                this.wait();
            }
            data[tail]=elem;
            tail++;
            if(tail>=data.length){
                tail=0;
            }
            size++;
            this.notify();
       }
    }
    public String take() throws InterruptedException {
        synchronized (this){
            while(size==0){
                this.wait();
            }
            String ret=data[head];
            head++;
            if(head>=data.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}
public class Demo29 {
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue(1000);
        Thread producer=new Thread(()->{
            int n=0;
            while(true){
                try {
                    queue.put(n+"");
                    System.out.println("生产者："+n);
                    n++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"producer");
        Thread consumer=new Thread(()->{
            while(true){
                try {
                    String n=queue.take();
                    Thread.sleep(1000);
                    System.out.println("消费者："+n);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"consumer");
        producer.start();
        consumer.start();
    }
}
